/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.labelimage.common.exception;


import com.labelimage.common.constant.HttpCode;
import com.labelimage.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;


import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * 异常处理器
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestControllerAdvice()
@Slf4j
public class LIExceptionHandler {


	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public  ResponseEntity<?> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
		log.info("请求方式错误:",e);
		return ResponseEntity.status(HttpCode.INPUT_INFO_ERROR.getValue()).body(Result.error("请求方式错误:"+e.getMessage()));
	}

	@ExceptionHandler(LIException.class)
	public ResponseEntity<?> handleAppException(LIException e){
		log.info("App自定义异常:",e);
		return ResponseEntity.status(e.getCode()).body(Result.error(e.getCode(),e.getMessage()));
	}

	@ExceptionHandler(BindException.class)
	public  ResponseEntity<?> handleBindException(BindException e){
		StringBuilder sb = new StringBuilder("参数错误:[");
		List<ObjectError> list = ((BindException) e).getAllErrors();
		for (ObjectError item : list) {
			sb.append(item.getDefaultMessage()).append(',');
		}
		sb.deleteCharAt(sb.length() - 1);
		sb.append(']');

		String msg = sb.toString();
		log.info(msg,e);
		return ResponseEntity.status(HttpCode.INPUT_INFO_ERROR.getValue()).body(Result.error(HttpCode.INPUT_INFO_ERROR.getValue(),msg));
	}


	@ExceptionHandler({ConstraintViolationException.class,MethodArgumentNotValidException.class})
	public  ResponseEntity<?> handleConstraintViolationException(Exception e){
		log.info("接口参数错误::",e);
		return ResponseEntity.status(HttpCode.INPUT_INFO_ERROR.getValue()).body(Result.error(HttpCode.INPUT_INFO_ERROR.getValue(),"接口参数错误:"+e.getMessage()));
	}


	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public Result<?>  handleException(Exception e){
		log.info("app服务未知异常:",e);
		return Result.error("app服务未知异常:"+e.getMessage());
	}
}
